package io.renren.modules.sys.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.common.utils.Tools;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.entity.MaterialEntity;
import io.renren.modules.sys.service.MaterialService;
import io.renren.modules.sys.service.MaterialcategoryService;
import io.renren.modules.sys.service.UnitService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 产品表
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-11-22 14:29:36
 */
@RestController
@RequestMapping("sys/material")
public class MaterialController {
    @Autowired
    private MaterialService materialService;
    @Autowired
    private MaterialcategoryService materialcategoryService;
    @Autowired
    private UnitService unitService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:material:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = materialService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/findByOrder")
    public R findByOrder(@RequestParam Map<String, Object> params) {
        String pageSize = "15";
        String pageNo = "1";
        Object pageSizeObj = params.get("pageSize");
        Object pageNoObj = params.get("pageNo");
        if (pageSizeObj != null) {
            pageSize = pageSizeObj.toString();
        }
        if (pageNoObj != null) {
            pageNo = pageNoObj.toString();
        }
        params.put("limit", pageSize);
        params.put("page", pageNo);

        ArrayList<String> columns = new ArrayList<>();
        columns.add("name");
        columns.add("model");
        Page<MaterialEntity> page = materialService.selectPage(
                new Query<MaterialEntity>(params).getPage(),
                new EntityWrapper<MaterialEntity>()
                        .orderAsc(columns)
        );

        PageUtils pageUtils = new PageUtils(page);

        List<MaterialEntity> list = (List<MaterialEntity>) pageUtils.getList();
        List<Long> longs = new ArrayList<>();
        for (MaterialEntity entity : list) {
            longs.add(entity.getId());
        }
        return R.ok().put("mIds", longs);
    }


    @RequestMapping("/findBy")
    public R findBy(@RequestParam Map<String, Object> params) {
        String pageSize = "15";
        String pageNo = "1";
        Object pageSizeObj = params.get("pageSize");
        Object pageNoObj = params.get("pageNo");
        if (pageSizeObj != null) {
            pageSize = pageSizeObj.toString();
        }
        if (pageNoObj != null) {
            pageNo = pageNoObj.toString();
        }
        params.put("limit", pageSize);
        params.put("page", pageNo);

        String categoryId = Tools.dealNullStr(params.get("CategoryId"));
        String categoryIds = Tools.dealNullStr(params.get("CategoryIds"));
        String name = Tools.dealNullStr(params.get("Name"));
        String model = Tools.dealNullStr(params.get("Model"));
        String mpList = Tools.dealNullStr(params.get("mpList"));
        String[] mpArr = mpList.split(",");
        Page<MaterialEntity> page = null;
        if ("1".equals(categoryId)) {

            page = materialService.selectPage(
                    new Query<MaterialEntity>(params).getPage(),
                    new EntityWrapper<MaterialEntity>()
                            .like("categoryId", categoryId)
                            .like("name", name)
                            .like("model", model)
                            .orderBy("id")
            );
        } else {
            page = materialService.selectPage(
                    new Query<MaterialEntity>(params).getPage(),
                    new EntityWrapper<MaterialEntity>()
                            .like("categoryId", categoryId)
                            .like("name", name)
                            .like("model", model)
                            .in("CategoryId", categoryIds)
                            .orderBy("id")
            );
        }

        PageUtils pageUtils = new PageUtils(page);

        List<MaterialEntity> list = (List<MaterialEntity>) pageUtils.getList();
        JSONArray dataArray = new JSONArray();
        if (null != list) {
            for (MaterialEntity material : list) {
                JSONObject item = new JSONObject();
                item.put("Id", material.getId());
                item.put("Name", material.getName());
                item.put("CategoryId", materialcategoryService.selectById(material.getCategoryid()).getId()); //类型Id
                item.put("CategoryName", materialcategoryService.selectById(material.getCategoryid()).getName()); //类型名称
                item.put("Packing", material.getPacking() == null ? "" : material.getPacking());
                item.put("SafetyStock", material.getSafetystock() == null ? "" : material.getSafetystock());
                item.put("Model", material.getModel() == null ? "" : material.getModel());
                //扩展信息
                String materialOther = "";
                for (int i = 0; i < mpArr.length; i++) {
                    if (mpArr[i].equals("颜色")) {
                        materialOther = materialOther + ((material.getColor() == null || material.getColor().equals("")) ? "" : "(" + material.getColor() + ")");
                    }
                    if (mpArr[i].equals("规格")) {
                        materialOther = materialOther + ((material.getStandard() == null || material.getStandard().equals("")) ? "" : "(" + material.getStandard() + ")");
                    }
                    if (mpArr[i].equals("制造商")) {
                        materialOther = materialOther + ((material.getMfrs() == null || material.getMfrs().equals("")) ? "" : "(" + material.getMfrs() + ")");
                    }
                    if (mpArr[i].equals("自定义1")) {
                        materialOther = materialOther + ((material.getOtherfield1() == null || material.getOtherfield1().equals("")) ? "" : "(" + material.getOtherfield1() + ")");
                    }
                    if (mpArr[i].equals("自定义2")) {
                        materialOther = materialOther + ((material.getOtherfield2() == null || material.getOtherfield2().equals("")) ? "" : "(" + material.getOtherfield2() + ")");
                    }
                    if (mpArr[i].equals("自定义3")) {
                        materialOther = materialOther + ((material.getOtherfield3() == null || material.getOtherfield3().equals("")) ? "" : "(" + material.getOtherfield3() + ")");
                    }
                }
                item.put("MaterialOther", materialOther);
                item.put("Unit", material.getUnit() == null ? "" : material.getUnit());
                item.put("RetailPrice", material.getRetailprice());
                item.put("LowPrice", material.getLowprice());
                item.put("PresetPriceOne", material.getPresetpriceone() == null ? "" : material.getPresetpriceone());
                item.put("PresetPriceTwo", material.getPresetpricetwo() == null ? "" : material.getPresetpricetwo());
                item.put("UnitId", material.getUnitid() == null ? "" : unitService.selectById(material.getUnitid()).getId()); //计量单位Id
                item.put("UnitName", material.getUnitid() == null ? "" : unitService.selectById(material.getUnitid()).getUname()); //计量单位名称
                item.put("FirstOutUnit", material.getFirstoutunit());
                item.put("FirstInUnit", material.getFirstinunit());
                item.put("PriceStrategy", material.getPricestrategy());
                item.put("Enabled", material.getEnabled());
                item.put("Remark", material.getRemark());
                item.put("Color", material.getColor() == null ? "" : material.getColor());
                item.put("Standard", material.getStandard() == null ? "" : material.getStandard());
                item.put("Mfrs", material.getMfrs() == null ? "" : material.getMfrs());
                item.put("OtherField1", material.getOtherfield1() == null ? "" : material.getOtherfield1());
                item.put("OtherField2", material.getOtherfield2() == null ? "" : material.getOtherfield2());
                item.put("OtherField3", material.getOtherfield3() == null ? "" : material.getOtherfield3());
                item.put("op", 1);
                dataArray.add(item);
            }
        }
        return R.ok().put("rows", dataArray).put("total", list.size());
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:material:info")
    public R info(@PathVariable("id") Long id) {
        MaterialEntity material = materialService.selectById(id);

        return R.ok().put("material", material);
    }

    @RequestMapping("/findById")
    public R findById(@PathVariable("id") Long MaterialID) {
        MaterialEntity material = materialService.selectById(MaterialID);

        return R.ok().put("material", material);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:material:save")
    public R save(@RequestBody MaterialEntity material) {
        materialService.insert(material);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:material:update")
    public R update(@RequestBody MaterialEntity material) {
        ValidatorUtils.validateEntity(material);
        materialService.updateAllColumnById(material);//全部更新

        return R.ok();
    }

    @RequestMapping("/batchSetEnable")
    public R batchSetEnable(String ids, boolean enabled) {
        String[] split = ids.split(",");
        for (String str : split) {
            MaterialEntity materialEntity = new MaterialEntity();
            materialEntity.setId(Long.valueOf(str));
            materialEntity.setEnabled(enabled);
            materialService.updateById(materialEntity);
        }

        return R.ok();
    }

    @RequestMapping("/checkIsExist")
    public Boolean checkIsExist(@RequestBody MaterialEntity material) {
        /**
         *         if (model.getMaterialID() > 0) {
         *             condition.put("ID_n_neq", model.getMaterialID());
         *         }
         *         condition.put("Name_s_eq", model.getName());
         *         condition.put("Model_s_eq", model.getModel());
         *         condition.put("Color_s_eq", model.getColor());
         *         condition.put("Standard_s_eq", model.getStandard());
         *         condition.put("Mfrs_s_eq", model.getMfrs());
         *         condition.put("OtherField1_s_eq", model.getOtherField1());
         *         condition.put("OtherField2_s_eq", model.getOtherField2());
         *         condition.put("OtherField3_s_eq", model.getOtherField3());
         *         if (model.getUnit() != null) {
         *             condition.put("Unit_s_eq", model.getUnit());
         *         }
         *         if (model.getUnitId() != null) {
         *             condition.put("UnitId_n_eq", model.getUnitId());
         *         }
         */
        int i = materialService.selectCount(new EntityWrapper<MaterialEntity>()
                .notLike("id", Tools.dealNullStr(material.getId()))
                .eq("name",material.getName())
                .eq("model",material.getModel())
                .eq("color",material.getColor())
                .eq("Standard",material.getName())
                .eq("Mfrs",material.getName())
                .eq("OtherField1",material.getName())
                .eq("OtherField2",material.getName())
                .eq("OtherField3",material.getName())
                .like("Unit",Tools.dealNullStr(material.getUnit()))
                .like("UnitId",Tools.dealNullStr(material.getUnitid()))
        );

        if (i > 0) {
            return true;
        }
        return false;
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:material:delete")
    public R delete(@RequestBody Long[] ids) {
        materialService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 查找商品信息-下拉框
     *
     * @return
     */
    @RequestMapping("/findBySelect")
    public JSONArray findBySelect(@RequestParam Map<String, Object> params) {
        String pageSize = "15";
        String pageNo = "1";
        Object pageSizeObj = params.get("pageSize");
        Object pageNoObj = params.get("pageNo");
        if (pageSizeObj != null) {
            pageSize = pageSizeObj.toString();
        }
        if (pageNoObj != null) {
            pageNo = pageNoObj.toString();
        }
        params.put("limit", pageSize);
        params.put("page", pageNo);
        Page<MaterialEntity> page = materialService.selectPage( new Query<MaterialEntity>(params).getPage(),
                new EntityWrapper<MaterialEntity>()
                        .eq("enabled",1)
                        .orderBy("id"));
        PageUtils pageUtils = new PageUtils(page);
        List dataList = pageUtils.getList();
        String mpList = (String)params.get("MpList")+""; //商品属性
        String[] mpArr = mpList.split(",");
        //存放数据json数组
        JSONArray dataArray = new JSONArray();
        if (null != dataList) {
            for (Object obj : dataList) {
                MaterialEntity material = (MaterialEntity) obj;
                JSONObject item = new JSONObject();
                item.put("Id", material.getId());
                String ratio; //比例
                if (material.getUnitid() == null || material.getUnitid().equals("")) {
                    ratio = "";
                } else {
                    ratio = material.getUnit();
                    ratio = ratio.substring(ratio.indexOf("("));
                }
                //品名/型号/扩展信息/包装
                String MaterialName = material.getName() + ((material.getModel() == null || material.getModel().equals("")) ? "" : "(" + material.getModel() + ")");
                for (int i = 0; i < mpArr.length; i++) {
                    if (mpArr[i].equals("颜色")) {
                        MaterialName = MaterialName + ((material.getColor() == null || material.getColor().equals("")) ? "" : "(" + material.getColor() + ")");
                    }
                    if (mpArr[i].equals("规格")) {
                        MaterialName = MaterialName + ((material.getStandard() == null || material.getStandard().equals("")) ? "" : "(" + material.getStandard() + ")");
                    }
                    if (mpArr[i].equals("制造商")) {
                        MaterialName = MaterialName + ((material.getMfrs() == null || material.getMfrs().equals("")) ? "" : "(" + material.getMfrs() + ")");
                    }
                    if (mpArr[i].equals("自定义1")) {
                        MaterialName = MaterialName + ((material.getOtherfield1() == null || material.getOtherfield1().equals("")) ? "" : "(" + material.getOtherfield1() + ")");
                    }
                    if (mpArr[i].equals("自定义2")) {
                        MaterialName = MaterialName + ((material.getOtherfield2() == null || material.getOtherfield2().equals("")) ? "" : "(" + material.getOtherfield2() + ")");
                    }
                    if (mpArr[i].equals("自定义3")) {
                        MaterialName = MaterialName + ((material.getOtherfield3() == null || material.getOtherfield3().equals("")) ? "" : "(" + material.getOtherfield3() + ")");
                    }
                }
                MaterialName = MaterialName + ((material.getUnit() == null || material.getUnit().equals("")) ? "" : "(" + material.getUnit() + ")") + ratio;
                item.put("MaterialName", MaterialName);
                dataArray.add(item);
            }
        }
        //回写查询结果
        return dataArray;

    }

}
